<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>003 补零</title>
</head>
<body>

  <h1>003 补零</h1>
  <p>所有不满 五位 的随机自然数，在前面补 0，满五位的不做处理</p>
  <p>如 11 则得到 "00011"，而 123456 则得到 "123456"</p>

  <form id="myform" method="get">
    <input type="text" name="num" value="123" placeholder="请随机输入数字...">
    <input type="submit" value="补零">
  </form>

  <script>
    document.getElementById("myform").addEventListener("submit", function(e) {
      //阻止默认提交行为.
      e.preventDefault();

      var result = "";
      var num = this.num.value;
      //任意长度.
      var max = 5;

      if( isNaN(parseInt(num)) ) {
        alert("请输入数字");
        return false;
      }

      result = Array(max - num.length + 1).join(0) + num;

      alert(result);

    }, false);
  </script>
  <script>
    /*
    document.getElementById("myform").addEventListener("submit", function(e) {
      //阻止默认提交行为.
      e.preventDefault();

      //获取数字.
      var num = this.num.value;
      var result = "";

      if( isNaN(parseInt(num)) ) {
        alert("请输入数字");
        return;
      }

      //5位补零技巧
      result = num.length <= 5
        ? ("00000" + num).substr(num.length) : num;

      alert(result);

    }, false);
    */
  </script>

</body>
</html>
